<template>
  <a-select
    v-model:value="_value"
    :token-separators="[',']"
    mode="tags"
    max-tag-count="responsive"
    placeholder="演员信息"
    class="w-[400px]"
    :options="dropDownData.options"
    :fieldNames="{ label: 'person_name', key: 'person_name', value: 'person_name' }"
    @change="handleActorChange"
    @dropdownVisibleChange="handleDropDownVisibleChange"
    @popupScroll="handlePopupScroll"
    :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
  >
    <template #dropdownRender="{ menuNode: menu }">
      <v-nodes :vnodes="menu" />
      <template class="flex justify-center">
        <a-spin :spinning="dropDownData.isLoading" tip="加载中" class="z-1000" />
      </template>
    </template>
  </a-select>
</template>
<script lang="ts" setup>
import { storage } from '@/utils/storage'
import { computed, nextTick, ref, toRefs } from 'vue'
//必须要写
const VNodes = (_: any, { attrs }: any) => {
  return attrs.vnodes
}
interface IPagination {
  total: number
  offset: number
  limit: number
}
interface IProps {
  placeholder: string
  apiUrl: any
  newValue: any
}
const props = withDefaults(defineProps<IProps>(), {
  placeholder: '演员信息',
  apiUrl: undefined
})
const { newValue } = toRefs(props)
const emit = defineEmits<{
  (e: 'update:newValue', val: number): void
  (e: 'get-list', val: any): void
  (e: 'handle-change', val: any): void
}>()
const dropDownData = ref<{ options: any[]; pagination: IPagination; isLoading: boolean }>({
  options: [], //下拉项列表
  pagination: {
    total: 0, //用于记录数据总长度,后期判断是否还继续加载
    offset: 0,
    limit: 10
  }, //分页器下拉
  isLoading: true //是否正在加载数据
})
const siteId = storage.get('siteId') //站点id
//演员change
const handleActorChange = (value: string[], option: any) => {
  console.log('value: ', value, option)
  option.forEach((item: any, index: number) => {
    if (!item.person_name && !item.person_id) {
      item.person_name = ''
      item.person_id = 0
    }
  })
  const arr = value.toString().split(',')
  option.forEach((item: any, index: number) => {
    item.person_name = arr[index]
  })
  // formState.actor = [...option]
  emit('handle-change', option)
}
const _value = computed({
  get: () => {
    return newValue.value
  },
  set: (val: number) => {
    emit('update:newValue', val)
  }
})
/* 下拉列表请求-初次的时候 */
const handleDropDownVisibleChange = async (open: boolean, type: number) => {
  if (open && dropDownData.value.options.length === 0) {
    //初次加载
    dropDownData.value.isLoading = true
    props.apiUrl({ site_id: siteId, ...dropDownData.value.pagination }).then((res: any) => {
      dropDownData.value.pagination.total = res.total ?? 0
      dropDownData.value.isLoading = false
      //从结果中map获取列表数据
      dropDownData.value.options =
        res?.persons?.map((item: any) => ({
          person_id: item.person_id ?? 0,
          person_name: item.person_name ?? ''
        })) ?? []
      emit('get-list', dropDownData.value.options)
    })
  }
}
const scrollT = ref(0)
/* 下拉滚动 */
const handlePopupScroll = async (e: any) => {
  //已经有的下拉项目 大于等于后台返回的下拉项总长度,那么就返回不请求了
  if (dropDownData.value.options.length >= dropDownData.value.pagination.total) return
  let { target } = e
  const scrollHeight = target.scrollHeight - target.scrollTop
  scrollT.value = target.scrollTop
  const clientHeight = target.clientHeight
  if (scrollHeight == clientHeight.toFixed(0)) {
    //到达了底部,请求数据
    dropDownData.value.pagination.offset += 10 //分页器自增10
    dropDownData.value.isLoading = true
    console.log('scrollT.value1: ', scrollT.value)
    props.apiUrl({ site_id: siteId, ...dropDownData.value.pagination }).then((res: any) => {
      //从结果中map获取列表数据
      const temp =
        res?.persons?.map((item: any) => ({
          person_id: item.person_id ?? 0,
          person_name: item.person_name ?? ''
        })) ?? []
      //注意顺序,这里是先解构之前的,再解构之后的
      dropDownData.value.options = [...dropDownData.value.options, ...temp]
      emit('get-list', dropDownData.value.options)
      dropDownData.value.isLoading = false
      nextTick(() => {
        target.scrollTop = scrollT.value
      })
    })
  }
}
</script>

<style lang="scss" scoped></style>
<!--
  <a-select
            v-model:value="formState.actor_copy"
            :token-separators="[',']"
            mode="tags"
            max-tag-count="responsive"
            placeholder="演员信息"
            class="w-[400px]"
            :options="dropDownData.options"
            :fieldNames="{ label: 'person_name', key: 'person_name', value: 'person_name' }"
            @change="handleActorChange"
            @dropdownVisibleChange="handleDropDownVisibleChange"
            @popupScroll="handlePopupScroll"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <template #dropdownRender="{ menuNode: menu }">
              <v-nodes :vnodes="menu" />
              <template class="flex justify-center">
                <a-spin :spinning="dropDownData.isLoading" tip="加载中..." class="z-1000" />
              </template>
            </template>
          </a-select>
 -->
